package org.gap.esupport;

import static org.gap.esupport.FeatureSupport.AVAILABLE_FEATURES;
import static org.gap.esupport.FeatureSupport.FEATURE_LOCATION;
import static org.gap.esupport.FeatureSupport.MAIN_WINDOW;
import static org.gap.esupport.FeatureSupport.PERFORM_SEARCH;
import static org.hamcrest.core.IsEqual.equalTo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.ListModel;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.collection.IsCollectionContaining;

import com.objogate.wl.Query;
import com.objogate.wl.swing.AWTEventQueueProber;
import com.objogate.wl.swing.driver.JButtonDriver;
import com.objogate.wl.swing.driver.JFrameDriver;
import com.objogate.wl.swing.driver.JListDriver;
import com.objogate.wl.swing.driver.JTextFieldDriver;
import com.objogate.wl.swing.gesture.GesturePerformer;

public class LocalFeatureApplication extends JFrameDriver {

	@SuppressWarnings("unchecked")
	public LocalFeatureApplication() {
		super(new GesturePerformer(), new AWTEventQueueProber(), named(MAIN_WINDOW), showingOnScreen());
	}
	
	public void readInFeaturesFrom(String location) {
		featureLocation().typeText(location);
		performSearch().click();
	}

	@SuppressWarnings("unchecked")
	private JButtonDriver performSearch() {
		return new JButtonDriver(this, JButton.class, named(PERFORM_SEARCH));
	}

	@SuppressWarnings("unchecked")
	private JTextFieldDriver featureLocation() {
		return new JTextFieldDriver(this, JTextField.class, named(FEATURE_LOCATION));
	}

	public void listsFeatures(String...featureNames) {
		availableFeatures().has(listedItems(), withFeatures(featureNames));
	}

	@SuppressWarnings("unchecked")
	private JListDriver availableFeatures() {
		return new JListDriver(this, JList.class, named(AVAILABLE_FEATURES));
	}

	private Query<JList, Collection<String>> listedItems() {
		return new Query<JList, Collection<String>>() {
			@Override
			public Collection<String> query(JList list) {
				ListModel model = list.getModel();
				List<String> result = new ArrayList<String>(model.getSize());
				for (int i = 0; i < model.getSize(); i++) {
					String each = (String)model.getElementAt(i);
					result.add(each);
				}
				return result;
			}
			@Override
			public void describeTo(Description arg0) {
				arg0.appendText("available feature list");
			}
		};
	}

	private Matcher<? super Collection<String>> withFeatures(final String[] featureNames) {
		return IsCollectionContaining.hasItems(featureNames);
	}

	@SuppressWarnings("unchecked")
	public void canvasHasPainted(String...features) {
		for (String each : features) {
			new JButtonDriver(this, JButton.class, named(each)).hasText(equalTo(each));
		}
	}

	public void canvasArrangesAbove(String string, String string2) {
		// TODO Auto-generated method stub
		
	}
}
